//
//  GSDKDatabaseManager.m
//  GameSDK
//
//  Created by Johnny on 2017/7/31.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKDatabaseManager.h"
#import "GSDKCommonMethod.h"
#import "FMDatabase.h"
#import "NSString+Extension.h"
#import "YYKit.h"
#import "GSDKEncryptionHelper.h"

static GSDKDatabaseManager *shared = nil;
@implementation GSDKDatabaseManager
+ (GSDKDatabaseManager *)shared {
    static dispatch_once_t pred;
    dispatch_once( &pred, ^{
        if (shared == nil) {
            shared = [[self alloc]init];
            [shared createTable];
        }
    });
    return shared;
}

- (NSArray *)selectUserWith:(NSString *)userName {
    NSMutableArray *users= [[NSMutableArray alloc] init];
    NSString * sql = @"";
    if (userName == nil) {
        sql = @"select * from UserTable where type = 1 or type = 2 order by datetime DESC";
    } else {
        sql = [NSString stringWithFormat:@"select * from UserTable where userName = '%@' order by datetime DESC", userName];
    }
    NSArray * items = [[GSDKDatabaseManager shared] executeQuery: sql];
    for (int i = 0; i < [items count]; i++) {
        [users addObject:[GSDKDatabaseManager getUser: items[i]]];
    }
    return users;
}

- (BOOL)insertUserWith:(GSDKUserAccountModel *)model {
    NSString * json = [GSDKDatabaseManager getJsonValue:model];
    return [[GSDKDatabaseManager shared] executeUpdate:[NSString stringWithFormat:@"replace into UserTable(userName,type,datetime,jsonValue) VALUES('%@', '%@', '%@','%@')", model.userName, @(model.type), @((long long)[model.datetime timeIntervalSince1970]), json]];
}

- (BOOL)deleteUserWith:(GSDKUserAccountModel *)model {
    return [[GSDKDatabaseManager shared] executeUpdate:[NSString stringWithFormat:@"DELETE FROM UserTable WHERE userName = '%@'", model.userName]];
}

- (NSArray *)selectAllIAP {
    NSMutableArray *products = [[NSMutableArray alloc] init];
    NSArray * items = [[GSDKDatabaseManager shared] executeQuery: @"select * from IAPTable order by datetime DESC"];
    for (int i = 0; i < [items count]; i++) {
        [products addObject:[GSDKDatabaseManager getProduct: items[i]]];
    }
    return products;
}

- (NSArray *)selectUnfinishedIAP {
    NSMutableArray *products = [[NSMutableArray alloc] init];
    NSArray * items = [[GSDKDatabaseManager shared] executeQuery: @"select * from IAPTable where code = 0 order by datetime DESC"];
    for (int i = 0; i < [items count]; i++) {
        [products addObject:[GSDKDatabaseManager getProduct: items[i]]];
    }
    return products;
}

- (NSArray *)selectIAPWith:(NSString *)iapID {
    NSMutableArray *products = [[NSMutableArray alloc] init];
    NSArray * items = [[GSDKDatabaseManager shared] executeQuery: [NSString stringWithFormat:@"select * from IAPTable where id = '%@'", iapID]];
    for (int i = 0; i < [items count]; i++) {
        [products addObject:[GSDKDatabaseManager getProduct: items[i]]];
    }
    return products;
}

- (BOOL)insertIAPWith:(GSDKProduct *)model {
    NSString * json = [GSDKDatabaseManager getJsonValue:model];
    return [[GSDKDatabaseManager shared] executeUpdate:[NSString stringWithFormat:@"replace into IAPTable(id,datetime,code,msg,jsonValue) VALUES('%@', '%@', '%@', '%@', '%@')", model.iapID, @((long long)[model.postDate timeIntervalSince1970]), @(model.code), model.msg, json]];
}

#pragma mark - sqlist
- (void)createTable {
    NSURL * url = [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
    NSString * path = [[url path] stringByAppendingPathComponent:@"SDKDATABASE.db"];
    DEBUGMSG(@"path-----%@",path);
    _db = [FMDatabase databaseWithPath:path];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path] == NO) {
        if ([_db open]) {
            BOOL rsUserTable = [_db executeUpdate:@"CREATE TABLE 'UserTable' ('userName' VARCHAR(255) PRIMARY KEY NOT NULL, 'type' INTEGER NOT NULL, 'datetime' INTEGER NOT NULL, 'jsonValue' TEXT NOT NULL)"];
            if (!rsUserTable) {
                DEBUGMSG(@"UserTable建表不成功");
            } else {
                DEBUGMSG(@"UserTable建表成功");
            }
            BOOL rsIAPTable = [_db executeUpdate:@"CREATE TABLE 'IAPTable' ('id' VARCHAR(255) PRIMARY KEY, 'datetime' INTEGER NOT NULL, 'code' INTEGER NOT NULL, 'msg' VARCHAR(255) NOT NULL, 'jsonValue' TEXT NOT NULL)"];
            if (!rsIAPTable) {
                DEBUGMSG(@"IAPTable建表不成功");
            } else {
                DEBUGMSG(@"IAPTable建表成功");
            }
        }
        [_db close];
    } else {
        DEBUGMSG(@"数据库已经存在");
    }
    if (![_db open]) {
        DEBUGMSG(@"不能打开db");
        return;
    }
}

- (NSArray *)executeQuery:(NSString *)query {
    FMResultSet *rs = [_db executeQuery:query];
    NSMutableArray *items= [[NSMutableArray alloc] init];
    while ([rs next]) {
        [items addObject:[rs stringForColumn:@"jsonValue"]];
    }
    [rs close];
    return items;
}

- (BOOL)executeUpdate:(NSString *)update {
    BOOL isUpdate = NO;
    [_db beginTransaction];
    if (![_db executeUpdate:update]) {
        isUpdate = NO;
    } else {
        isUpdate = YES;
    }
    [_db commit];
    return isUpdate;
}

#pragma mark - 数据处理
+ (NSString *)getJsonValue:(NSObject *)model {
    return [GSDKEncryptionHelper encryptBase64WithString: [model modelToJSONString]];
}

+ (GSDKUserAccountModel *)getUser:(NSString *)json {
    return [GSDKUserAccountModel modelWithJSON: [GSDKEncryptionHelper decodeBase64WithString:json]];
}

+ (GSDKProduct *)getProduct:(NSString *)json {
    return [GSDKProduct modelWithJSON: [GSDKEncryptionHelper decodeBase64WithString:json]];
}

@end
